define(function(require, exports) {
	var c1 = require('c1');

	var c1Page = {};

	c1Page = {
		isInit : false,
		init : function(fn) {
			c1Page.fn = fn;

			if (!this.isInit) {
				$(document).on("click", 'form[name="usGroupUserNewForm"] .c1-save', c1Page.saveClick);

				$(document).on("click", 'form[name="usGroupUserNewForm"] .c1-back', c1Page.backClick);

				this.isInit = true;
			}

			c1Page.initTypeahead('form[name="usGroupUserNewForm"]');
		},
		saveClick : function() {
			c1.message.progress();

			var url = $('form[name="usGroupUserNewForm"]').attr('action');

			if ($('form[name="usGroupUserNewForm"] input[name="userGroupCode"]').val() == '') {
				$('form[name="usGroupUserNewForm"] input[name="userGroupId"]').val('');
			}

			if ($('form[name="usGroupUserNewForm"] input[name="userCode"]').val() == '') {
				$('form[name="usGroupUserNewForm"] input[name="userId"]').val('');
			}

			var data = c1.form.serializeJson('form[name="usGroupUserNewForm"]');

			$.post(url, data, function(data) {
				c1.message.progress('close');

				if (data.code != '0') {
					c1.message.alert({
						title : '提示消息',
						message : data.message
					});

					return;
				}

				c1.message.alert({
					title : '提示消息',
					message : data.message,
					fn : function() {
						if ($.isFunction(c1Page.fn)) {
							c1Page.fn();
						}

						c1Page.backClick();
					}
				});
			});
		},
		initTypeahead : function(selector) {
			require('bootstrap-typeahead');

			$(selector).find('input[name="userGroupCode"]').typeahead({
				source : function(query, process) {
					var url = cardone.webContextUrl + '/authority/userGroup/findListByLikeCode.json';

					$.post(url, {
						'code' : query
					}, function(data) {
						process($.map(data.data, function(item) {
							var text = item.name + '(' + item.code + '), id:' + item.id;

							return text;
						}));
					});
				},
				updater : function(item) {
					var items = item.split(', id:');

					$(selector).find('input[name="userGroupId"]').val(items[1]);

					return items[0];
				}
			});

			$(selector).find('input[name="userCode"]').typeahead({
				source : function(query, process) {
					var url = cardone.webContextUrl + '/usercenter/user/findListByLikeCode.json';

					$.post(url, {
						'code' : query
					}, function(data) {
						process($.map(data.data, function(item) {
							var text = item.name + '(' + item.code + '), id:' + item.id;

							return text;
						}));
					});
				},
				updater : function(item) {
					var items = item.split(', id:');

					$(selector).find('input[name="userId"]').val(items[1]);

					return items[0];
				}
			});
		},
		backClick : function() {
			$('.c1-modal').modal('hide').find('.modal-body').html('');
		}
	};

	return {
		init : c1Page.init
	};
});